package com.brook.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Brook
 * set user info
 */
@Configuration
public class DemoApplicationConfiguration {

    /**
     * add user of security
     * @return
     */
    @Bean
    public UserDetailsService myUserDetailsService() {

        Logger logger = LoggerFactory.getLogger(DemoApplicationConfiguration.class);

        //Store user info in memory
        InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
        //builder user info
        String[][] usersGroupAndRoles= {
                {"jack","password","ROLE_ACTIVITI_USER","GROUP_activitiTeam"},
                {"rose","password","ROLE_ACTIVITI_USER","GROUP_activitiTeam"},
                {"tom","password","ROLE_ACTIVITI_USER","GROUP_activitiTeam"},
                {"jerry","password","ROLE_ACTIVITI_USER","GROUP_activitiTeam"},
                {"other","password","ROLE_ACTIVITI_USER","GROUP_otherTeam"},
                {"system","password","ROLE_ACTIVITI_USER"},
                {"admin","password","ROLE_ACTIVITI_ADMIN"}
        };

        for (String[] user : usersGroupAndRoles) {
            //Roles and groups of Users
            List<String> authStrList = Arrays.asList(Arrays.copyOfRange(user, 2, user.length));
            logger.info("> Registering new user: " + user[0] + " with the following Authorities[" + authStrList + "]");
            userDetailsManager.createUser(new User(user[0],
                    passwordEncoder().encode(user[1]),
                    authStrList.stream().map(str -> new SimpleGrantedAuthority(str)).collect(Collectors.toList())));
        }
        return userDetailsManager;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
